package org.nuplay;
import java.net.InetAddress;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JProgressBar;

public class NuPlayAudioSend implements Runnable, LineListener {

	private boolean stopped;
	private TargetDataLine line;
	private int treshold;
	private NuPlayConnector connector;
	private JProgressBar indicator;
	
	
	public NuPlayAudioSend(TargetDataLine in_line, AudioFormat format, int level, Integer channel, InetAddress address, JProgressBar in_indicator_audio) {
		System.out.println("NuPlayAudioSend");
		connector = new NuPlayConnector(address, channel);
		indicator = in_indicator_audio;
		line = in_line;
		treshold = level;
		line.addLineListener(this);
		try {
			line.open(format);
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Begin audio capture.
		line.start();
		stopped = false;
		Thread thread = new Thread(this);
		thread.start();
	}

	public void setLevel(int in_level) {
		this.treshold = in_level;
	}
	
	public void run() {
		int numBytesRead;
		System.out.println(line.getBufferSize());
		byte[] data = new byte[line.getBufferSize() / 50];
		while (!stopped) {
			numBytesRead =  line.read(data, 0, data.length);
			int samples = 0;
			for(int j = 0; j < numBytesRead; j++) {
				samples += (data[j] * data[j]);
			}
			int level = new Double(Math.sqrt(samples / numBytesRead)).intValue();
			indicator.setValue(level);
			if (level >= treshold) {
				if (connector.isBelowThreshold()) {
					connector.sendOn(level);
				}
			} else if (!connector.isBelowThreshold()) {
				connector.sendOff(level);
			}
		}  
		indicator.setValue(0);
		connector.close();
	}

	public void close() {
		stopped = true;
	}


	public void update(LineEvent arg0) {
	}

}
